package Review;

public class Test37 {

	public static void main(String[] args) {

	}
     public static ListNode findFirstCommonNode(ListNode head1,ListNode head2){
    	 ListNode p1 = head1;
    	 int len1 = 0;
    	 while(p1!=null){
    		 len1++;
    		 p1 = p1.next;
    	 }
    	 ListNode p2 = head2;
    	 int len2 = 0;
    	 while(p2!=null){
    		 len2++;
    		 p2=p2.next;
    	 }
    	 int k = len1 - len2;
    	 ListNode pLong = head1;
    	 ListNode pShort = head2;
    	 if(len1<len2){
    		 k = len2-len1;
    		 pLong = head2;
        	 pShort = head1;
    	 }
    	 for(int i=1;i<=k;i++){
			 pLong=pLong.next;
    	 }
    	 while(pLong!=null&&pShort!=null&&pLong!=pShort){
    		 pLong = pLong.next;
    		 pShort = pShort.next;
    	 }
    	 return pLong;
     }
     
}

class CommonNode{
	public ListNode findFirstCommonNode(ListNode list1,ListNode list2){
		if(list1 == null || list2 == null){
			return null;
		}
		ListNode p1 = list1,pLong = list1;
		ListNode p2 = list2,pShort = list2;
		int len1 = 0;
		while(p1 != null){
			len1 ++;
			p1 = p1.next;
		}
		int len2 = 0;
		while(p2 != null){
			len2 ++;
			p2 = p2.next;
		}
		int k = len1 - len2;
		if(len2 > len1){
			pLong = list2;
			pShort = list1;
			k = len2 - len1;
		}
		int i = 0;
		while(i < k){
			pLong = pLong.next;
			i ++ ;
		}
		while(pLong!=null&&pShort!=null&&pLong!=pShort){
   		 pLong = pLong.next;
   		 pShort = pShort.next;
   	 }
   	 return pLong;
	}
}